package com.my.lucky.controller;

import com.my.lucky.config.IwencaiConfig;
import com.my.lucky.entity.StockQueryRecord;
import com.my.lucky.entity.SysInfo;
import com.my.lucky.model.*;
import com.my.lucky.repository.ReviewInfoRepository;
import com.my.lucky.repository.SysInfoRepository;
import com.my.lucky.service.IWencaiServiceTools;
import com.my.lucky.service.ReviewInfoService;
import com.my.lucky.service.StockMonitorService;
import com.my.lucky.util.DataUtil;
import com.my.lucky.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/api/iwencai")
public class IwencaiController {

    @Autowired
    private IWencaiServiceTools iwencaiService;
    @Autowired
    private StockMonitorService monitorService;
    @Autowired
    private IwencaiConfig iwencaiConfig;
    @Autowired
    private SysInfoRepository sysInfoRepository;

    @Autowired
    private ReviewInfoRepository reviewInfoRepository;;


    @GetMapping("/search")
    public List<Map<String, Object>> searchStocks(@RequestParam String keyword) {
        log.info("搜索关键词: {}", keyword);
        return iwencaiService.searchStocks(keyword, iwencaiConfig.getIsLocal());
    }

    @GetMapping("/config")
    public ConfigResponse getDefaultConfig(@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate) {
        ConfigResponse response = new ConfigResponse();
        List<SysInfo> sysInfos = sysInfoRepository.findAll();
        if (sysInfos != null && sysInfos.size() > 0) {
            for (SysInfo info : sysInfos) {
                if ("focusStocks".equals(info.getSysKey())) {
                    response.setFocus(info.getSysValue());
                }

                if ("focusGainian".equals(info.getSysKey())) {
                    response.setFocusGainian(info.getSysValue());
                    iwencaiConfig.setFocusGaiNian(info.getSysValue());
                }

                if ("allOptional".equals(info.getSysKey())) {
                    response.setAllOptional(info.getSysValue());
                }
            }
        }

        response.setFocusBoll(iwencaiConfig.getFocusBoll());
        if (startDate==null){
            startDate = LocalDate.now();
        }
        String review="";
        for (int i = 0; i < 25; i++) {
            ReviewInfo reviewInfo = reviewInfoRepository.findFirstByReviewTime(startDate.minusDays(i));
            if (reviewInfo!=null) {
                String rcontent="";
                if(reviewInfo.getReviewContent()!=null){
                    rcontent =reviewInfo.getReviewContent().trim();
                }
                review+=rcontent+";时间#"+ DateUtils.toYmdHms(reviewInfo.getUpdateTime())+";概念#"+ DataUtil.processConcepts(reviewInfo.getReviewGainian())+";个股#"+DataUtil.processConcepts(reviewInfo.getReviewStock())+"\n";
            }
        }
//        System.out.println(review);
        response.setReviewCon(review);

        List<StockQueryRecord> records =iwencaiConfig.getNow10Drecords();;

        if (records != null) {
            String stockCodes = records.stream()
                    // 提取每个对象的stockCode
                    .map(StockQueryRecord::getStockCode)
                    // 过滤可能的null值（可选，根据实际情况）
                    .filter(Objects::nonNull)
                    // 去除重复的股票代码
                    .distinct()
                    // 用逗号连接所有股票代码
                    .collect(Collectors.joining(","));
            response.setSearchtr(stockCodes);
        }


//        System.out.println(sysInfos);
//        response.setFocus(iwencaiConfig.getFocus());
//        response.setFocusGainian("支付");
//        response.setSearchKeyword(iwencaiConfig.getSearchKeyword());
//        response.setGainianKeyword(iwencaiConfig.getGainianKeyword());
        response.setSearchInterval(iwencaiConfig.getSearchInterval());
        response.setGainianInterval(iwencaiConfig.getGainianInterval());
        response.setHotInterval(iwencaiConfig.getHotInterval());
        response.setBaseDataInterval(iwencaiConfig.getBaseDataInterval());

        // 从数据库读取时间配置
        List<SysInfo> allConfigs = sysInfoRepository.findAllBy();
        Map<String, String> configMap = allConfigs.stream().collect(java.util.stream.Collectors.toMap(SysInfo::getSysKey, SysInfo::getSysValue));

        response.setSearchKeyword(configMap.getOrDefault("searchKeyword", "概念主力增仓上涨,日线KDJ向上或日线KDJ的J线高于K线,周线KDJ向上或周线KDJ的J线高于K线,月线KDJ向上,60分钟周期分时KDJ向上,15分钟周期分时KDJ的J线向上,放量"));
        response.setGainianKeyword(configMap.getOrDefault("gainianKeyword", "所属概念日线KDJ向上,所属概念日线KDJ的J线高于K线,概念指数"));

        response.setMorningStart(configMap.getOrDefault("morningStart", "09:00"));
        response.setMorningEnd(configMap.getOrDefault("morningEnd", "11:30"));
        response.setAfternoonStart(configMap.getOrDefault("afternoonStart", "13:00"));
        response.setAfternoonEnd(configMap.getOrDefault("afternoonEnd", "15:00"));
        response.setEnableTimeControl("true".equals(configMap.getOrDefault("enableTimeControl", "true")));
        return response;
    }

    @PostMapping("/monitor")
    public MonitorResponse monitor(@RequestBody MonitorRequest request) {
        return monitorService.monitor(request.getFocusStocks(), request.getIwencaiKeyword());
    }

    @PostMapping("/gainian")
    public GainianResponse updateGainianKeyword(@RequestBody GainianRequest request) {
        GainianResponse response = new GainianResponse();
        try {
            List<Map<String, Object>> maps = iwencaiService.searchGainian(request.getGainianKeyword());
            response.setSuccess(true);
            response.setGainian(maps);
        } catch (Exception e) {
            response.setSuccess(false);
            response.setMessage("更新概念提示词失败：" + e.getMessage());
        }
        return response;
    }
} 